package com.sun.handle;


import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.util.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/** 配置拦截器
 * @author shkstart
 * @create 2021-09-21 17:28
 */
@Component
public class JwtTokenInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader("token");
        Map map=new HashMap<String,Object>();
        try {
            JwtUtils.verify(token);
            return true;
        }catch (TokenExpiredException e){
            map.put("state",false);
            map.put("msg","Token已经过期");
        }catch (SignatureVerificationException e){
            map.put("state",false);
            map.put("msg","签名错误");
        }catch (AlgorithmMismatchException e){
            map.put("state",false);
            map.put("msg","加密算法不匹配");
        }catch (Exception e){
            e.printStackTrace();
            map.put("state",false);
            map.put("msg","无效token");
        }
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}
